var logger = require('./logger');
const WebSocket = require('ws');
var userList = require('./websocketManage/userList');
var User = require('./websocketManage/user');
module.exports = function(server, app) {
    var userId = null;
    var wss = new WebSocket.Server({server});
    wss.on('connection', function connection(client, req) {
        // console.log('wss--req--', req);
        const ip = req.connection.remoteAddress;
        console.log('ip---', ip);
        client.on('open', function open() {
            console.log('---wss--open---');
            client.send('something');

        });
        
        client.on('message', function(data) {
            console.log('on:message', data);
            var msg = JSON.parse(data);
            msg.userId = app.locals.user._id;
            console.log('type--', msg.type);
            switch(msg.type)  {
                case 'join': 
                    userJoin(msg);
                    break;
                case 'leave':
                
                    userLeave(msg);
                    break;    
            }
            client.send('dd');
        });

        client.on('error', function(data) {
            console.log('error----', data);
        });

        client.on('close', function(e, res) {
            console.log('close-data---', e);
            console.log('websocket close!');
        });

    })
}


// 用户进入
function userJoin(user) {
    logger.info(user.userId + '进入聊天室！');
    var user = new User({
        userId: user.userId,
        clientId: user.clientId
    })
    userList.addUser(user);
    console.log('userList--', userList.getUserList());
    console.log('user---', user);
}

// 用户离开
function userLeave(user) {
    logger.info(user.userId + '离开聊天室！');
    userList.removeUser(user);
}